﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using OpticalPowerMeter.UserControls;
using System.Threading;

namespace OpticalPowerMeter
{
    /// <summary>
    /// CheckGroupWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CheckGroupWindow : Window
    {
        public CheckGroupWindow()
        {
            InitializeComponent();
            InitWavelengthList();
            InitGroupList();
        }

        //初始化可选波长列表
        private void InitWavelengthList()
        {
            List<MyWavelength> wavelengthList = WavelengthListManagement.GetInstance().GetWavelengthList();
            foreach (MyWavelength myWavelength in wavelengthList) {
                CheckBox checkBox = new CheckBox();
                checkBox.Content = myWavelength.Wavelength;
                checkBox.HorizontalAlignment = HorizontalAlignment.Left;
                checkBox.VerticalAlignment = VerticalAlignment.Top;
                WavelengthGrid.Children.Add(checkBox);
                checkBox.Checked += new RoutedEventHandler(WavelengthChecked);
                checkBox.Unchecked += new RoutedEventHandler(WavlengthUnchecked);
            }
        }

        //复选按钮选中时显示绿色，并刷新复查列表项
        private void WavelengthChecked(object sender, RoutedEventArgs args)
        {
            CheckBox checkBox = sender as CheckBox;
            checkBox.Foreground = Brushes.Green;
            string wavelength = checkBox.Content.ToString();
            AddCheckListItem(wavelength);
        }

        //添加波长对应的检查点
        private void AddCheckListItem(string wavlength) {
            TabItem tabItem = new TabItem();
            Label title = new Label();
            title.Content = wavlength;
            title.FontSize = 18;
            tabItem.Header = title;
            ScrollViewer scrollViewer = new ScrollViewer();
            scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
            Grid grid = new Grid();
            grid.SizeChanged += GridSizeChanged;
            scrollViewer.Content = grid;
            tabItem.Content = scrollViewer;
            #region 把控件按照波长排序后，插入相应位置
            int insertIndex = 0;
            int intWave = Convert.ToInt32(wavlength);
            foreach (TabItem tab in CheckTab.Items) {
                int tabWave = Convert.ToInt32(((Label)tab.Header).Content);
                if (tabWave > intWave)
                {
                    break;
                }
                insertIndex++;
            }
            CheckTab.Items.Insert(insertIndex,tabItem);
            #endregion
            tabItem.IsSelected = true;
            //启动线程刷新检查列表
            Thread initCheckListThread = new Thread(InitCheckList);
            initCheckListThread.Start(wavlength);
        }

        //TabItem下的Grid尺寸变化时，刷新子控件(CheckControl)尺寸及位置
        private void GridSizeChanged(object sender,SizeChangedEventArgs args)
        {
            Grid source = sender as Grid;
            double gridWidth = source.ActualWidth;
            if(gridWidth < 10)
            {
                return;
            }
            for(int i = 0; i < source.Children.Count; i++)
            {
                CheckControl checkControl = (CheckControl)source.Children[i];
                checkControl.Width = gridWidth;
                checkControl.Height = gridWidth / 12;
                checkControl.Margin = new Thickness(0, gridWidth / 12 * i, 0, 0);
            }
        }


        //初始化波长对应的检查点清单
        private void InitCheckList(object wavelengthObj) {
            string wavelength = wavelengthObj as string;
            App.Current.Dispatcher.BeginInvoke(new Action(()=> { 
                #region 获取该波长对应的Item，如果不存在，则直接返回 
                Grid tabGrid = null;
                foreach(TabItem item in CheckTab.Items)
                {
                    if (((Label)item.Header).Content.Equals(wavelength))
                    {
                        tabGrid = (Grid)((ScrollViewer)item.Content).Content;
                        break;
                    }
                }
                if (tabGrid == null)
                {
                    return;
                }
                #endregion
                #region 将检查清单添加到控件列表，如果不存在时，添加一个空的控件
                string groupname = GroupNameTextBox.Text.Trim().ToUpper();
                List<CheckPoint> checkList = CheckGroupManagement.GetInstance().GetCheckList(groupname, wavelength); 
                if (checkList == null || checkList.Count == 0)
                {
                    CheckControl checkControl = new CheckControl();
                    checkControl.ButtonClicked += CheckButton_Click;
                    checkControl.HorizontalAlignment = HorizontalAlignment.Left;
                    checkControl.VerticalAlignment = VerticalAlignment.Top;
                    double width = tabGrid.ActualWidth;
                    if (width > 10)
                    {
                        checkControl.Width = width;
                        checkControl.Height = width / 10;
                    }
                    tabGrid.Children.Add(checkControl);
                    return;
                }
                for (int i=0;i<checkList.Count;i++) {
                    CheckControl checkControl = new CheckControl();
                    checkControl.ButtonClicked += CheckButton_Click;
                    checkControl.HorizontalAlignment = HorizontalAlignment.Left;
                    checkControl.VerticalAlignment = VerticalAlignment.Top;
                    double width = tabGrid.ActualWidth;
                    tabGrid.Children.Add(checkControl);
                    if (width > 10)
                    {
                        checkControl.Width = width;
                        checkControl.Height = width / 12;
                        checkControl.Margin = new Thickness(0, width / 12 * i, 0, 0);
                    }
                    double power = checkList[i].CheckPoint_P;
                    double limit_H = checkList[i].Limit_H;
                    double limit_L = checkList[i].Limit_L;
                    checkControl.CheckPower = power.ToString();
                    checkControl.Limit_H = limit_H.ToString();
                    checkControl.Limit_L = limit_L.ToString();
                }
                #endregion
            }));
        }


        //加减按钮点击时，删除或添加控件
        private void CheckButton_Click(object sender,CheckControlClickedArgs args) {
            CheckControl checkControl = sender as CheckControl;
            Grid parentGrid = (Grid)checkControl.Parent; //父框架
            UIElementCollection uIElementCollection = parentGrid.Children;
            int index = uIElementCollection.IndexOf(checkControl); //当前控件在列表中的位置
            //#region 当前控件所在位置，及尺寸信息
            Thickness controlMargin = checkControl.Margin;
            double controlLeft = controlMargin.Left;
            double controlTop = controlMargin.Top;
            double controlRight = controlMargin.Right;
            double controlBottom = controlMargin.Bottom;
            double controlWidth = checkControl.ActualWidth;
            double controlHeight = checkControl.ActualHeight;
            //#endregion
            string changeType = args.ChangeType;
            if (changeType.Equals("Add"))
            {
                #region 移动下面的控件位置
                for (int i = index + 1; i < uIElementCollection.Count; i++)
                {
                    CheckControl currentControl = (CheckControl)uIElementCollection[i];
                    Thickness currentMargin = currentControl.Margin;
                    double cuurrentLeft = currentMargin.Left;
                    double currentTop = currentMargin.Top;
                    double currentRight = currentMargin.Right;
                    double currentBottom = currentMargin.Bottom;
                    currentControl.Margin = new Thickness(cuurrentLeft, currentTop + controlHeight, currentRight, currentBottom);
                }
                #endregion
                #region 添加新控件
                CheckControl newControl = new CheckControl();
                newControl.ButtonClicked += CheckButton_Click;
                newControl.HorizontalAlignment = HorizontalAlignment.Left;
                newControl.VerticalAlignment = VerticalAlignment.Top;
                newControl.Height = controlHeight;
                newControl.Width = controlWidth;
                newControl.Margin = new Thickness(controlLeft, controlTop + controlHeight, controlRight, controlBottom);
                uIElementCollection.Insert(index + 1, newControl);
                #endregion
            }
            else
            {
                #region 至少保留一个控件
                if (uIElementCollection.Count == 1)
                {
                    return;
                }
                #endregion
                uIElementCollection.RemoveAt(index); //移除当前控件
                #region 把当前控件下面的控件上移
                for (int i = index; i < uIElementCollection.Count; i++)
                {
                    CheckControl currentLinear = (CheckControl)uIElementCollection[i];
                    Thickness currentMargin = currentLinear.Margin;
                    double currentLeft = currentMargin.Left;
                    double currentTop = currentMargin.Top;
                    double currentRight = currentMargin.Right;
                    double currentBottom = currentMargin.Bottom;
                    currentLinear.Margin = new Thickness(currentLeft, currentTop - controlHeight, currentRight, currentBottom);
                }
                #endregion
            }
        }

        //复选按钮未选中时显示黑色，并刷新复查列表项
        private void WavlengthUnchecked(object sender, RoutedEventArgs args)
        {
            CheckBox checkBox = sender as CheckBox;
            checkBox.Foreground = Brushes.Black;
            string wavelength = checkBox.Content.ToString();
            foreach(TabItem wavelengthItem in CheckTab.Items)
            {
                string tabHead = (string)((Label)wavelengthItem.Header).Content;
                if (tabHead == wavelength)
                {
                    CheckTab.Items.Remove(wavelengthItem);
                    return;
                }
            }
        }

        #region 绑定显示的属性
        //清单表头字号
        static DependencyProperty DataGridHeadFontProperty = DependencyProperty.Register(
            "DataGridHeadFont",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //单元字号
        static DependencyProperty CellFontProperty = DependencyProperty.Register(
            "CellFont",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //单元高度
        static DependencyProperty CellHeightProperty = DependencyProperty.Register(
            "CellHeight",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //数据列宽
        static DependencyProperty DataGridColumnWidthProperty = DependencyProperty.Register(
            "DataGridColumnWidth",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //复查组字号
        static DependencyProperty GroupNameFontSizeProperty = DependencyProperty.Register(
            "GroupNameFontSize",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //复查组输入框高度
        static DependencyProperty GroupNameBoxHeightProperty = DependencyProperty.Register(
            "GroupNameBoxHeight",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //复查组输入框宽度
        static DependencyProperty GroupNameBoxWidthProperty = DependencyProperty.Register(
            "GroupNameBoxWidth",
            typeof(double),
            typeof(CheckGroupWindow)
            );

        //复查组输入框边距
        static DependencyProperty GroupNameBoxMarginProperty = DependencyProperty.Register(
            "GroupNameBoxMargin",
            typeof(Thickness),
            typeof(CheckGroupWindow)
            );

        //保存按钮的边距
        static DependencyProperty SaveButtonMarginProperty = DependencyProperty.Register(
            "SaveButtonMargin",
            typeof(Thickness),
            typeof(CheckGroupWindow)
            );

        //删除按钮的边距
        static DependencyProperty DeleteButtonMarginProperty = DependencyProperty.Register(
            "DeleteButtonMargin",
            typeof(Thickness),
            typeof(CheckGroupWindow)
            );
        #endregion

        //尺寸发生变化时，调整控件尺寸
        private void Size_Changed(object sender, SizeChangedEventArgs args)
        {
            #region 刷新左侧列表字号等内容
            Grid parentGrid = (Grid)CheckGroupDataGrid.Parent;
            double parentWidth = parentGrid.ActualWidth;
            CheckGroupDataGrid.Width = parentWidth;
            double dataGridWidth = parentWidth;
            SetValue(DataGridColumnWidthProperty, dataGridWidth);  //设置列宽
            double height = dataGridWidth / 5; //宽度与高度比5:1
            double headFontSize = Math.Round((height - 10) / 1.27, 1);  //head字号
            SetValue(DataGridHeadFontProperty, headFontSize);
            SetValue(CellFontProperty, headFontSize - 2); //内容比head小2个字号
            SetValue(CellHeightProperty, Math.Round((headFontSize - 2) * 1.27, 1));
            #endregion
            #region 刷新检查组部分字号及边距等
            double groupNameGridWidth = GroupNameGrid.ActualWidth;
            double groupNameFontSize = Math.Round((groupNameGridWidth * 0.3 - 10) / 4, 1);  //线性组名称占总宽度30%
            SetValue(GroupNameFontSizeProperty, groupNameFontSize);
            double productNameBoxWidth = Math.Round(groupNameGridWidth * 0.7 - 20, 1);
            double productNameBoxHeight = Math.Round(groupNameFontSize * 1.27);
            SetValue(GroupNameBoxHeightProperty, productNameBoxHeight); //线性组名输入框的尺寸
            SetValue(GroupNameBoxWidthProperty, productNameBoxWidth);
            double boxLeft = Math.Round(groupNameGridWidth * 0.3 + 10, 1);
            SetValue(GroupNameBoxMarginProperty, new Thickness(boxLeft, 0, 0, 0));
            #endregion
            #region 刷新按钮部分边距
            double saveButtonLeft = Math.Round(groupNameGridWidth / 5, 1);
            SetValue(SaveButtonMarginProperty, new Thickness(saveButtonLeft, 0, 0, 0));
            double deleteButtonLeft = Math.Round(groupNameGridWidth / 5 * 3, 1);
            SetValue(DeleteButtonMarginProperty, new Thickness(deleteButtonLeft, 0, 0, 0));
            #endregion
            #region 调整波长列表字号及位置
            double wavelengthCheckBoxFontSize1 = headFontSize - 2;
            double wavelengthParentWidth = (groupNameGridWidth - 1) * 0.3; //父框架宽度
            double wavelengthCheckBoxFontSize2 = (wavelengthParentWidth - 20) / 2.34;
            double wavelengthCheckBoxFontSize = wavelengthCheckBoxFontSize1 > wavelengthCheckBoxFontSize2 ? wavelengthCheckBoxFontSize2: wavelengthCheckBoxFontSize1;
            UIElementCollection waveElementCollection = WavelengthGrid.Children; //获取控件清单
            //遍历复选按钮设置字号
            foreach (UIElement element in waveElementCollection)
            {
                if (element.GetType().Name.EndsWith("CheckBox"))
                {
                    CheckBox check = element as CheckBox;
                    check.FontSize = wavelengthCheckBoxFontSize;
                }
            }
            System.Threading.Thread thread = new System.Threading.Thread(ChangeMargin);
            thread.Start();
            #endregion
        }

        //刷新波长选择框的位置
        private void ChangeMargin()
        {
            App.Current.Dispatcher.Invoke(new Action(() => {
                UIElementCollection waveElementCollection = WavelengthGrid.Children; //获取控件清单
                List<CheckBox> checkBoxList = new List<CheckBox>();
                foreach (UIElement element in waveElementCollection)
                {
                    if (element.GetType().Name.EndsWith("CheckBox"))
                    {
                        CheckBox check = element as CheckBox;
                        checkBoxList.Add(check);
                    }
                }
                double wavelengthCheckBoxFontSize = checkBoxList[0].FontSize;
                double wavelengthParentWidth = WavelengthGrid.ActualWidth; //父框架宽度
                double wavelengthParentHeight = WavelengthGrid.ActualHeight; //父框架高度
                double boxWidth = wavelengthCheckBoxFontSize * 2.35; //控件宽度
                double boxHeight = ((CheckBox)waveElementCollection[0]).ActualHeight; //控件高度
                double spaceWidth = wavelengthParentWidth - boxWidth ; //放置完控件以后剩余的空白部分
                double leftMargin = spaceWidth / 2; //与左边控件的左边距
                for (int i = 0; i < checkBoxList.Count; i++)
                {
                    checkBoxList[i].Margin = new Thickness(leftMargin, i * boxHeight, 0, 0);
                }
            }));
        }

        private void CheckGroupDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs args) { 
            string groupname= CheckGroupDataGrid?.SelectedValue?.ToString().Trim();
            if (groupname == null || groupname == "")
            {
                return;
            }
            GroupNameTextBox.Text = groupname;
            List<string> checkWavelengthList = CheckGroupManagement.GetInstance().GetWavelengthList(groupname); //获取该组对应的选中的波长清单
            foreach(CheckBox wavelengthCheckBox in WavelengthGrid.Children)
            {
                string currentWavelength = wavelengthCheckBox.Content.ToString();
                if (checkWavelengthList.Contains(currentWavelength))
                {
                    wavelengthCheckBox.IsChecked = true;
                }
                else
                {
                    wavelengthCheckBox.IsChecked = false;
                }
            }
        }


        //保存数据
        private void SaveButton_Click(object sender,RoutedEventArgs args) {
            string groupname = GroupNameTextBox.Text.Trim();
            if (groupname == "")
            {
                MessageBox.Show("检查组名称不能为空","检查在名称为空",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }
            ItemCollection itemCollection = CheckTab.Items;
            Dictionary<string, List<CheckPoint>> checkListDic = new Dictionary<string, List<CheckPoint>>(); //KEY - 波长 , Value - 检查点清单
            foreach(TabItem item in itemCollection)
            {
                string wavelength = (string)((Label)(item.Header)).Content; //波长
                Grid parentGrid = (Grid)((ScrollViewer)item.Content).Content;
                List<CheckPoint> checkList = new List<CheckPoint>();
                foreach (CheckControl checkBox in parentGrid.Children) {
                    string power = checkBox.CheckPower;
                    string limit_L = checkBox.Limit_L;
                    string limit_H = checkBox.Limit_H;
                    if(power == "" || limit_L == "" || limit_H == "")
                    {
                        continue;
                    }
                    CheckPoint newCheckPoint = new CheckPoint();
                    newCheckPoint.CheckPoint_P = Convert.ToDouble(power);
                    newCheckPoint.Limit_L = Convert.ToDouble(limit_L);
                    newCheckPoint.Limit_H = Convert.ToDouble(limit_H);
                    checkList.Add(newCheckPoint);
                }
                if (checkList.Count > 0)
                {
                    checkListDic.Add(wavelength, checkList);
                }
            }
            CheckGroupManagement.GetInstance().SaveCheckList(groupname, checkListDic); //保存检查点信息至本地
            MessageBox.Show($"成功保存检查组{groupname}!", "保存检查组", MessageBoxButton.OK, MessageBoxImage.Information);
            InitGroupList();
        }


        //刷新检查组清单
        private void InitGroupList()
        {
            List<string> groupnameList = CheckGroupManagement.GetInstance().GetGroupnameList();
            CheckGroupDataGrid.ItemsSource = null;
            CheckGroupDataGrid.ItemsSource = groupnameList;
        }

        //删除组
        private void DeleteButton_Click(object sender,RoutedEventArgs args) {
            string groupname = GroupNameTextBox.Text.Trim();
            MessageBoxResult result = MessageBox.Show($"是否确定删除检查组{groupname}?","删除检查组",MessageBoxButton.YesNo,MessageBoxImage.Question);
            if (result != MessageBoxResult.Yes)
            {
                return;
            }
            CheckGroupManagement.GetInstance().DeleteGroup(groupname);
            MessageBox.Show($"成功删除检查组{groupname}!","删除检查组",MessageBoxButton.OK,MessageBoxImage.Information);
            InitGroupList();
        }
    }
}
